#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

#include "lib.h"

int do_login(int sockfd)
{
    char name[20] = {0};
    char passwd[20] = {0};
    printf("username:");fflush(stdout);
    gets(name);
    write(sockfd, name, 20);

    printf("passwd:");fflush(stdout);
    gets(passwd);
    write(sockfd, passwd, 20);

    char flag = 0;
    read(sockfd, &flag, 1);
    if(flag == 1)   
        return 0;
    else
        return -1;
}

char do_register(int sockfd)
{    
    char name[20] = {0};
    char passwd[20] = {0};
    printf("username:");fflush(stdout);
    gets(name);
    write(sockfd, name, 20);

    printf("passwd:");fflush(stdout);
    gets(passwd);
    write(sockfd, passwd, 20);

    char flag = 0;
    read(sockfd, &flag, 1);
    return flag;
}

void fill_args(char *p[],  char *buf)
{
    while(*buf)
    {
        if(*buf!=' ' && *(buf-1)==' ')
        {
            *p++ = buf;
            *(buf-1) = 0;
        }

        buf++;
    }
}

void do_get(int sockfd)
{
    char buff[2000];
    int n = read(sockfd, buff, 100);
    if(0 == strncmp(buff, "get e",5))
    {
        printf("%s\n",buff);
    }
    else
    {
        int fd = open(args[1], O_CREAT | O_WRONLY | O_TRUNC, 0666);
        int filesize = *((int *)buff);
        float p = filesize / 100.0;
        int size = 0;

        printf("file size is %.2f KB.\n",filesize/1024.0);
        while(n = read(sockfd, buff, 1500))
        { 
            size+=n;
   //         float b = (float)size / p;
            printf("\r%.1f%%.", size / p);
            write(fd, buff, n);
            if(size == filesize) //若接收完毕，则跳出循环，如果不这样判断，在没有受到数据时，read不会返回
            {
                break;
            }
        }
        puts("");
    }

}

int do_put(int sockfd)
{
    int fd = open(args[1], O_RDONLY); //打开文件出错,返回错误消息
    if(-1 == fd)
    {
        perror("Error");
        return -1;
    }
    else
    {
        int n;
        write(sockfd, buff, 100);
    }
    struct stat file_info;
    int file_size; 
    if(-1 == stat(args[1],&file_info))
    {
        perror("file stat");
    }
    file_size = file_info.st_size;
    
    write(sockfd, &file_size, 100); //先发送文件大小
    int n;
    float p = file_size / 100.0;
    int size = 0;
    while(n = read(fd, buff, 1500)) //循环发送文件,直到发完
    {
        size+=n;
        write(sockfd, buff, n);
        printf("\r%.1f%%",size / p);
    }
    puts("");
    return 0;
}

void do_ls(int sockfd)
{
    char bf[500];
    write(sockfd, buff, 100);
    read(sockfd,bf,500);
    printf("%s",bf);
    puts("");

}

